<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Area extends Model
{
    protected $table = 'area';

    public static function getIdByName($name,$field = 'id')
    {
        $area = self::where('name', trim($name))->first();
        if ($area) {
            if(array_key_exists($field,$area->toArray())){
                return $area[$field];
            }
        }
        return $area;
    }

    public function express()
    {
        return $this->belongsToMany(Area::class, 'express_area', 'express_id', 'area_id');
    }

    public function getAreaList($area_id=0,$take=500)
    {
        $data = $this->orderBy('id','asc')->take($take)->get()->toArray();
        $data = $this->get_attr($data,$area_id);
        return $data;
    }
    //一般传进三个参数。默认Parent_id=0；
    public function get_attr($a,$parent_id){
        $tree = array();                                //每次都声明一个新数组用来放子元素
        foreach($a as $v){
            if($v['parent_id'] == $parent_id){                      //匹配子记录
                $v['children'] = $this->get_attr($a,$v['id']); //递归获取子记录
                $tree[] = $v;                           //将记录存入新数组
            }
        }
        return $tree;                                  //返回新数组
    }

    protected function get_name($id){
        $r = $this->find($id);
        return $r['name'];
    }

}
